//
//  DeviceVC.swift
//  CleanMan
//
//  Created by whale on 2022/9/8.
//

import UIKit
import YYText
import SystemConfiguration.CaptiveNetwork
class DeviceVC: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title = "设备"
        start()
        
//        self.lbl.numberOfLines = 0
//        self.view.addSubview(self.lbl)
//        self.lbl2.numberOfLines = 0
//        self.view.addSubview(self.lbl2)
        
        listV.backgroundColor = .white
        self.view.addSubview(listV)
        listV.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height - UIScreen.navH - UIScreen.tabBarH)
        
        let rea = Network.reachability
        let data = [
            DeviceModel(name: "当前版本号：", icon: "curr_v", content: Bundle.main.version),
            DeviceModel(name: "设备名称：", icon: "device_name", content: UIDevice.current.name),
            DeviceModel(name: "系统版本：", icon: "sys_v", content: UIDevice.current.systemVersion),
            DeviceModel(name: "设备型号：", icon: "device_model", content: UIDevice.current.mode),
            
            
        ]
        var data2 = [
            DeviceModel(name: "连接状态：", icon: "net_status", content: rea?.isConnectedToNetwork == true ? "已连接" : "未连接"),
                     
                     DeviceModel(name: "当前连接网络：", icon: "net_link", content: rea?.isConnectedToNetwork == true ? (rea?.isWWAN == true ? "蜂窝网络" : (getWiFiName() ?? "WIFI")) : "无")
        ]
        if rea?.isReachableViaWiFi == true {
            data2.append(DeviceModel(name: "当前IP地址：", icon: "net_ip", content: getLocalIPAddressForCurrentWiFi() ?? ""))
        }
        data2.append(DeviceModel(name: "当前电池电量：", icon: "icon_battery", content: "\((UIDevice.current.batteryLevel*100))%"))
        
        
        listV.configData(data: [
            DeviceSectionModel(name: "版本信息", rows: data),
            DeviceSectionModel(name: "网络信息", rows: data2)
        ], cellType: HeadTailCell.self, cellForRow: { path, md, cell in
            guard let cell = cell as? HeadTailCell, let mod = md as? DeviceModel else { return }
            cell.v.config(title: mod.name, content: mod.content, hasArrow: false)
        }) { path, md in
            
        }
        
    }
    
    
    private func setup() {
        let t1 = Bundle.main.name.text(font: .font(18), color: .hex(0x333333))
        t1.yy_appendString("\n")
        
        t1.append(getText(title: "当前版本号：", content: Bundle.main.version))
        t1.append(getText(title: "设备名称：", content: UIDevice.current.name))
        t1.append(getText(title: "系统版本：", content: UIDevice.current.systemVersion))
        t1.append(getText(title: "设备型号：", content: UIDevice.current.mode))
        t1.yy_lineSpacing = 8.adapter
        let s = t1.size(maxSize: CGSize(width: view.bounds.width - 24.adapter, height: CGFloat.greatestFiniteMagnitude))
        self.lbl.attributedText = t1
        self.lbl.frame = CGRect(x: 12.adapter, y: UIScreen.navH, width: view.bounds.width - 24.adapter, height: s.height)
    }
    
    private func setupWifi() {
        
        let rea = Network.reachability
        
        let t1 = "网络信息".text(font: .font(18), color: .hex(0x333333))
        t1.yy_appendString("\n")
        
        t1.append(getText(title: "连接状态：", content: rea?.isConnectedToNetwork == true ? "已连接" : "未连接"))
        
        t1.append(getText(title: "当前连接网络：", content: rea?.isConnectedToNetwork == true ? (rea?.isWWAN == true ? "蜂窝网络" : (getWiFiName() ?? "WIFI")) : "无"))
        if rea?.isReachableViaWiFi == true {
            t1.append(getText(title: "当前IP地址：", content: getLocalIPAddressForCurrentWiFi() ?? ""))
        }
        t1.append(getText(title: "当前电池电量：", content: "\((UIDevice.current.batteryLevel*100))%"))
        t1.yy_lineSpacing = 8.adapter
        let s = t1.size(maxSize: CGSize(width: view.bounds.width - 24.adapter, height: CGFloat.greatestFiniteMagnitude))
        self.lbl2.attributedText = t1
        self.lbl2.frame = CGRect(x: 12.adapter, y: self.lbl.frame.maxY + 20.adapter, width: view.bounds.width - 24.adapter, height: s.height)
    }
    
    private func getText(title: String, content: String)-> NSMutableAttributedString {
        let t2 = title.text(font: .font(16), color: .hex(0x333333))
        let t3 = content.text(font: .font(15), color: .hex(0x999999))
        t2.append(t3)
        t2.yy_appendString("\n")
        return t2
    }
    
    private func getWiFiName() -> String? {
            guard let unwrappedCFArrayInterfaces = CNCopySupportedInterfaces() else {
    //            print("this must be a simulator, no interfaces found")
                return nil
            }
            guard let swiftInterfaces = (unwrappedCFArrayInterfaces as NSArray) as? [String] else {
    //            print("System error: did not come back as array of Strings")
                return nil
            }
            var wifiName: String?
            for interface in swiftInterfaces {
                print("Looking up SSID info for \(interface)") // en0
                guard let unwrappedCFDictionaryForInterface = CNCopyCurrentNetworkInfo(interface as CFString) else {
    //                print("System error: \(interface) has no information")
                    return nil
                }
                guard let SSIDDict = (unwrappedCFDictionaryForInterface as NSDictionary) as? [String: AnyObject] else {
    //                print("System error: interface information is not a string-keyed dictionary")
                    return nil
                }
                wifiName = (SSIDDict["SSID"] as? String)
            }
            return wifiName
        }
    
    // 获取当前wifi的IP地址
       func getLocalIPAddressForCurrentWiFi() -> String? {
           var address: String?
           
           // get list of all interfaces on the local machine
           var ifaddr: UnsafeMutablePointer<ifaddrs>? = nil
           guard getifaddrs(&ifaddr) == 0 else {
               return nil
           }
           guard let firstAddr = ifaddr else {
               return nil
           }
           for ifptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) {
               
               let interface = ifptr.pointee
               
               // Check for IPV4 or IPV6 interface
               let addrFamily = interface.ifa_addr.pointee.sa_family
               if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) {
                   // Check interface name
                   let name = String(cString: interface.ifa_name)
                   if name == "en0" {
                       
                       // Convert interface address to a human readable string
                       var addr = interface.ifa_addr.pointee
                       var hostName = [CChar](repeating: 0, count: Int(NI_MAXHOST))
                       getnameinfo(&addr, socklen_t(interface.ifa_addr.pointee.sa_len), &hostName, socklen_t(hostName.count), nil, socklen_t(0), NI_NUMERICHOST)
                       address = String(cString: hostName)
                   }
               }
           }

           freeifaddrs(ifaddr)
           return address
       }
    
    @objc private func networkChanged() {
        DispatchQueue.main.async {
            self.setupWifi()
        }
    }

    private func start() {
        NotificationCenter.default.addObserver(self, selector: #selector(networkChanged), name: .flagsChanged, object: nil)
        UIDevice.current.isBatteryMonitoringEnabled = true
        do {
            Network.reachability = try Reachability(hostname: "www.google.com")
            do {
                try Network.reachability?.start()
            } catch let error as Network.Error {
                print(error)
            } catch {
                print(error)
            }
        } catch {
            print(error)
        }

    }

    private lazy var lbl = YYLabel()
    
    private lazy var lbl2 = YYLabel()
    
    private lazy var listV = GroupedListView()

    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

struct DeviceSectionModel: GroupedListModelProtocol {
    var headerV: GroupedListSectionView?
    
    var footerV: GroupedListSectionView?
    
    var headerHeight: CGFloat?
    
    var footerHeight: CGFloat?
    
    var rowHeight: CGFloat?
    
    var rows: [TableCellModelProtocol]?
    
    var headerVType: GroupedListSectionView.Type?
    
    var footerVType: GroupedListSectionView.Type?
    
    var cellType: WhaleListCell.Type?
    
    init(name: String, rows: [DeviceModel]) {
        
        headerHeight = 38.adapter
        let header = DeviceSectionView()
        header.md = name
        headerV = header
        rowHeight = 56.adapter
        self.rows = rows
    }
}

struct DeviceModel: TableCellModelProtocol {
    var rowHeight: CGFloat?
    
    var cellType: WhaleListCell.Type?
    
    var name: String
    var icon: String
    var content: String
    

}
